//
//  YFLocationManager.m
//  project
//
//  Created by yefei on 2019/4/30.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFLocationManager.h"


@interface YFLocationManager () <AMapLocationManagerDelegate>

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, copy) PositionInfo positionInfo;

@end

@implementation YFLocationManager

#pragma mark - 绝对单例
static YFLocationManager *_manager = nil;
+ (instancetype)shared {
    
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}

- (instancetype)copyWithZone:(NSZone *)zone {
    return _manager;
}

- (instancetype)mutableCopyWithZone:(NSZone *)zone {
    return _manager;
}

#pragma mark - 单次定位
- (void)onceLocating:(PositionInfo)completion {
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (completion) {
            completion(location, regeocode, error.localizedDescription);
        }
    }];
}

#pragma mark - 持续定位
- (void)continuedLocating:(PositionInfo)completion {
    [self.locationManager startUpdatingLocation];
    self.positionInfo = completion;
}




#pragma mark - AMapLocationManagerDelegate
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager*)locationManager {
    [locationManager requestWhenInUseAuthorization];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode {
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    if (reGeocode) {
        NSLog(@"reGeocode:%@", reGeocode);
    }
    if (self.positionInfo) {
        self.positionInfo(location, reGeocode, nil);
    }
}
-(void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    LKLog(@"定位失败，请重新定位");
}

#pragma mark - Lazy Load
- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = AMapLocationManager.new;
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationManager.distanceFilter = kCLLocationAccuracyBest;
        _locationManager.locationTimeout = 10;
        _locationManager.reGeocodeTimeout = 10;
        _locationManager.distanceFilter = 50;
        _locationManager.delegate = self;
    }
    return _locationManager;
}


@end
